package com.zhu.util;

import java.io.*;

/**
 * Created by DELL on 2015/12/31.
 */
public class ObjectUtil {

    public static byte[] objectToByteArray(Object obj){
        if(obj == null){
            return null;
        }

        ObjectOutputStream out = null;
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        try{
            out = new ObjectOutputStream(byteOut);
            out.writeObject(obj);

            return byteOut.toByteArray();
        }catch(Exception e){
           e.printStackTrace();
        }finally{
            if(null != out){
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

        return null;
    }

    public static <T> T byteArrayToObject(byte[] byteArr){
        if(null == byteArr || byteArr.length == 0){
            return null;
        }

        ObjectInputStream in = null;
        try{
            in = new ObjectInputStream(new ByteArrayInputStream(byteArr));
            Object obj = in.readObject();

            if(obj != null){
                return (T)obj;
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            if(null != in){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

}
